#include <REGX52.H>
sbit RS = P3 ^ 1;
sbit E = P3 ^ 2;

void delays(unsigned char time);    //定义延时函数
void write_com(unsigned int com);   //写指令
void write_data(unsigned char dat); //写数据
void lcd_init();                    //lcd初始化
void Timer0_init();                 //定时器初始化
void index_bit();                   //计算位函数
unsigned char unindex[8];           //定义显示数组下标数组
unsigned char hour = 0, min = 0, scand = 0, en0_tmp = 0, en0_tmp2 = 0;  //定义时分秒及计数器中间变量

//定义lcd显示数据
unsigned char code table[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a};
void lcd_show();    //定于lcd显示函数
void main()
{
    lcd_init();
    Timer0_init();  //定时器初始化
    index_bit();    //计算数组下标
    lcd_show();
    while (1)
    {
        index_bit();
    }
}
void lcd_show()
{
    unsigned int i;
//    write_com(0x01);
    write_com(0xc4);    //定义显示位置
    for (i = 0; i < 8; i++)
    {
        write_data(table[unindex[i]]);
        delays(5);
    }
}

void write_com(unsigned int com) //写指令
{
    E = 0;  //打开使能信号，写入com数据
    RS = 0; //设置向lcd写入指令
    P0 = com;   //将要写入的值赋值给P0口
    delays(5);
    E = 1;  //关闭使能端口
    delays(5);
    E = 0;
}
void lcd_init() //lcd初始化
{
    E = 0;
    write_com(0x38); //开显示
    write_com(0x0c); //开显示不显示光标
    write_com(0x06); //写一个字符指针加1
    write_com(0x01); //清屏
    write_com(0xc4); //设置数据指针起点 设置第一行第一列
}

void write_data(unsigned char dat)
{
    E = 0;      //打开使能信号
    RS = 1;     //从lcd读信号
    P0 = dat;   //将要写入的值赋值给P0口
    delays(5);
    E = 1;
    delays(5);
    E = 0;
}

void index_bit() //计算位函数
{
    if (scand == 60)
    {
        min++;
        scand = 0;
        if (min == 60)
        {
            hour++;
            min = 0;
            if (hour == 24)
            {
                hour = 0;
            }
        }
    }
    unindex[0] = hour / 10;
    unindex[1] = hour % 10;
    unindex[2] = 10;
    unindex[3] = min / 10;
    unindex[4] = min % 10;
    unindex[5] = 10;
    unindex[6] = scand / 10;
    unindex[7] = scand % 10;
}

void Timer0_init() //定时器初始化
{
    TMOD = 0x01;
    TH0 = (65536 - 1000) / 256;
    TL0 = (65536 - 1000) % 256;
    ET0 = 1;
    TF0 = 0;
    EA = 1;
    TR0 = 1;
}

void en0() interrupt 1 //定时器响应函数
{
    en0_tmp++;
    TH0 = (65536 - 1000) / 256;
    TL0 = (65536 - 1000) % 256;
    TF0 = 0;
    if (en0_tmp == 100) //累计100ms秒加1
    {
        en0_tmp2++;
        en0_tmp = 0;
        if (en0_tmp2 == 10)
        {
            scand++;
            en0_tmp2 =0;
            lcd_show(); //设置秒改变时刷新一次lcd
            
        }
        
    }
}

void delays(unsigned char time)
{
    unsigned int i, j;
    for (i = 0; i < time; i++)
    {
        for (j = 0; j < 123; j++)
        {
        }
    }
}